//
//  SearchViewController.m
//  GC_OC
//
//  Created by 曾 on 2022/1/16.
//

#import "SearchViewController.h"
#import "SearchHistoryView.h"
#import "SearchHotView.h"
#import "SearchTableViewCell.h"
#import "IQKeyboardManager.h"
#import "TeacherViewController.h"
@interface SearchViewController ()<SearchHistoryViewDelegate,SearchHotViewDelegate,UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong)UITextField* filed;
@property (nonatomic, assign)NSInteger   index;
@property (nonatomic, strong)NSMutableArray* btnArr;
@property (nonatomic, strong)SearchHistoryView* history;
@property (nonatomic, strong)SearchHotView*     hotSearch;
@property (nonatomic, strong)UITableView*       tableview;
@property (nonatomic, strong)ObjectAFNetWorking* objectAFN;
@property (nonatomic, strong)NSMutableArray*     dataSource;
@end

@implementation SearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor whiteColor];
    self.btnArr=[NSMutableArray new];
    self.dataSource=[NSMutableArray new];
    self.objectAFN=[[ObjectAFNetWorking alloc]init];
    [self creatHeadView];
    self.index=[[NSUserDefaults standardUserDefaults] integerForKey:@"selectType"];
    //
    CGFloat height=[GC_OCTool getHeightForLabel:@"A" andFont: [UIFont fontWithName:@"Helvetica-Bold" size:FontSize(10)] andWidth:wid(100)]+wid(20);
    NSArray* array=@[@"标题",@"文稿内容"];
    CGFloat width1=[GC_OCTool getWidthForLabel:array[0] andFont:[UIFont fontWithName:@"Helvetica-Bold" size:FontSize(10)] andHeight:wid(100)]+height;
    CGFloat width2=[GC_OCTool getWidthForLabel:array[1] andFont:[UIFont fontWithName:@"Helvetica-Bold" size:FontSize(10)] andHeight:wid(100)]+height;
    CGFloat jx=((SCREEN_WIDTH-width1-height-width2-height)-wid(110)*2.0);
    for (int i=0;i<2;i++)
    {
        CGFloat width=[GC_OCTool getWidthForLabel:array[i] andFont:[UIFont fontWithName:@"Helvetica-Bold" size:FontSize(10)] andHeight:wid(100)]+height;
        UIButton* btn=[[UIButton alloc]initWithFrame:CGRectMake(wid(110)+i*(jx+width),topHeight+wid(20),width,height+wid(20))];
        UIImageView* smllImage=[[UIImageView alloc]initWithFrame:CGRectMake(0,(btn.frame.size.height-(height-wid(20)))/2.0,height-wid(20),height-wid(20))];
        [btn addSubview:smllImage];
        UILabel* titleLabel=[[UILabel alloc]initWithFrame:CGRectMake(height,0,width,btn.frame.size.height)];
        titleLabel.text=array[i];
        titleLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:FontSize(10)];
        [btn addSubview:titleLabel];
        [self.view addSubview:btn];
        titleLabel.tag=100;
        smllImage.tag=101;
        titleLabel.textColor=RBG(220,220,220);
        smllImage.image=[UIImage imageNamed:@"未选中"];
        if(i==self.index)
        {
            titleLabel.textColor=RBG(46,125,250);
            smllImage.image=[UIImage imageNamed:@"选中"];
        }
        btn.tag=200+i;
        [btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.btnArr addObject:btn];
    }
    [self.view addSubview:self.history];
    [self.view addSubview:self.hotSearch];
    _tableview=[[UITableView alloc]initWithFrame:CGRectMake(0,topHeight+height+wid(20)+wid(20),SCREEN_WIDTH,SCREEN_HEIGHT-(topHeight+height+wid(20)+wid(20))) style:UITableViewStylePlain];
    _tableview.tableFooterView=[[UIView alloc]initWithFrame:CGRectZero];
    _tableview.dataSource=self;
    _tableview.delegate=self;
    [_tableview registerNib:[UINib nibWithNibName:@"SearchTableViewCell" bundle:nil] forCellReuseIdentifier:@"SearchTableViewCell"];
    _tableview.alpha=0;
    [self.view addSubview:_tableview];
    self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    [IQKeyboardManager sharedManager].shouldShowToolbarPlaceholder = NO;
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

-(void)handleSingleTap
{
    [self.filed resignFirstResponder];
}
-(void)getData
{
    _hotSearch.alpha=0;
    _history.alpha=0;
    _tableview.alpha=1;
    NSString* urlStr;
    NSString *filePath;
    if(self.index==0)
    {
        urlStr=[NSString stringWithFormat:@"%@/api/index/AudioList?title=%@",server_addr,self.filed.text];
        filePath = [NSHomeDirectory() stringByAppendingString:[NSString stringWithFormat: @"/Documents/search_file_%@_title_Json.json",self.filed.text]];
    }else
    {
        urlStr=[NSString stringWithFormat:@"%@/api/index/AudioList?introduce=%@",server_addr,self.filed.text];
        filePath = [NSHomeDirectory() stringByAppendingString:[NSString stringWithFormat: @"/Documents/search_file_%@_ntroduce_Json.json",self.filed.text]];
    }
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath]) {
        NSData* dataString=[NSData dataWithContentsOfFile:filePath];
        NSDictionary* dic=[NSJSONSerialization JSONObjectWithData:dataString options:NSJSONReadingMutableContainers error:nil];
        [self.dataSource removeAllObjects];
        //清空
        [self.dataSource addObjectsFromArray:dic[@"data"][@"video"]];
        [self.tableview reloadData];
        [GC_OCTool saveFileAction:filePath];
    }else
    {
        NSString* encodedString = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        [self.objectAFN getUrlStr:encodedString finish:^(id  _Nonnull dataString) {
            NSDictionary* dic=[NSJSONSerialization JSONObjectWithData:dataString options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"%@",dic);
            BOOL code = [dic[@"code"] boolValue];
            if (code) {
                [self.dataSource removeAllObjects];
                //清空
                [self.dataSource addObjectsFromArray:dic[@"data"][@"video"]];
                [self.tableview reloadData];
            }
            [self.tableview reloadData];
            if ([fileManager fileExistsAtPath:filePath]) {
                [fileManager removeItemAtPath:filePath error:nil];
            }
            [dataString writeToFile:filePath atomically:YES];

            
        } andError:^(NSError * _Nonnull error) {
            
        }];
    }
}
#pragma mark - tableview delegate and datasource
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat titleHeight=[GC_OCTool getHeightForLabel:@"A" andFont:[UIFont systemFontOfSize:FontSize(12)] andWidth:wid(100)];
    return (wid(20)+titleHeight*2+wid(20)+wid(10));
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataSource.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SearchTableViewCell* cell=[tableView dequeueReusableCellWithIdentifier:@"SearchTableViewCell"];
    [cell initView:self.dataSource[indexPath.row] andIndex:self.index andSearchStr:self.filed.text];
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    return cell;
}
-(void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
    TeacherViewController* teacher=[[TeacherViewController alloc]init];
    teacher.dic=self.dataSource[indexPath.row];
    [self.navigationController pushViewController:teacher animated:YES];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
-(SearchHistoryView*)history
{
    if(!_history)
    {
        _history=[[SearchHistoryView alloc]initWithFrame:CGRectMake(0,topHeight+wid(100),SCREEN_WIDTH,wid(10))];
        _history.myDelegate=self;
    }
    return _history;
}
-(SearchHotView*)hotSearch
{
    if(!_hotSearch)
    {
        _hotSearch=[[SearchHotView alloc]initWithFrame:CGRectMake(0,_history.frame.origin.y+_history.frame.size.height,SCREEN_WIDTH,wid(10))];
        _hotSearch.myDelegate=self;
    }
    return _hotSearch;
}
-(void)upDateUI
{
    //获取数据
    [_history getData];
    //刷新位置
    _hotSearch.frame=CGRectMake(0,_history.frame.origin.y+_history.frame.size.height,SCREEN_WIDTH,_hotSearch.frame.size.height);
    [self.filed resignFirstResponder];
}
-(void)upDateText:(NSString*)text
{
    self.filed.text=text;
    [self getData];
}
-(void)btnAction:(UIButton*)sender
{
    for (int i=0;i<self.btnArr.count;i++)
    {
        UIButton* btn=self.btnArr[i];
        UILabel* label=[btn viewWithTag:100];
        UIImageView* img=[btn viewWithTag:101];
        label.textColor=RBG(220,220,220);
        img.image=[UIImage imageNamed:@"未选中"];
    }
    UIButton* btn=self.btnArr[sender.tag-200];
    UILabel* label=[btn viewWithTag:100];
    UIImageView* img=[btn viewWithTag:101];
    label.textColor=RBG(46,125,250);
    img.image=[UIImage imageNamed:@"选中"];
    self.index=sender.tag-200;
    [[NSUserDefaults standardUserDefaults]setInteger:self.index forKey:@"selectType"];
    if(self.filed.text.length>0)
    {
        [self getData];
    }
}
-(void)creatHeadView
{
    UIView* view=[[UIView alloc]initWithFrame:CGRectMake(0,0,SCREEN_WIDTH,topHeight)];
    view.backgroundColor=AppMainColor;
    CGFloat widht=[GC_OCTool getWidthForLabel:@"取消" andFont:[UIFont fontWithName:@"Helvetica-Bold" size:FontSize(12)] andHeight:wid(100)]+wid(40);
    UIView* centView=[[UIView alloc]initWithFrame:CGRectMake(wid(80),StatusBarHeight+(topHeight-StatusBarHeight-wid(55))/2.0,SCREEN_WIDTH-wid(80)-widht,wid(55))];
    centView.backgroundColor=RBG(218,218,218);
    centView.layer.masksToBounds=YES;
    centView.layer.cornerRadius=wid(55)/2.0;
    self.filed=[[UITextField alloc]initWithFrame:CGRectMake(wid(20),0,centView.frame.size.width-wid(40),wid(55))];
    self.filed.font=[UIFont systemFontOfSize:FontSize(12)];
    NSAttributedString* attrString=[[NSAttributedString alloc]initWithString:@"搜索其实很简单" attributes:@{
        NSForegroundColorAttributeName:RBG(150,150,150),
        NSFontAttributeName:[UIFont systemFontOfSize:FontSize(12)]
    }];
    self.filed.textColor=[UIColor blackColor];
    self.filed.attributedPlaceholder=attrString;
    self.filed.delegate=self;
    [centView addSubview:self.filed];
    [self.filed addTarget:self action:@selector(changedTextValue:) forControlEvents:UIControlEventEditingChanged];
    [self.filed.keyboardToolbar.doneBarButton setTarget:self action:@selector(doneAction)];
    
    [view addSubview:centView];
    
    UIButton* leftbtn=[UIButton new];
    leftbtn.frame=CGRectMake(wid(20),StatusBarHeight+(topHeight-StatusBarHeight-wid(40))/2.0,wid(40),wid(40));
    [leftbtn setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [leftbtn addTarget:self action:@selector(leftBtnAction) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton* rightbtn=[UIButton new];
    rightbtn.frame=CGRectMake(SCREEN_WIDTH-widht,StatusBarHeight+(topHeight-StatusBarHeight-wid(40))/2.0,widht,wid(40));
    [rightbtn setTitle:@"取消" forState:UIControlStateNormal];
    [rightbtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    rightbtn.titleLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:FontSize(12)];
    [rightbtn addTarget:self action:@selector(rightBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:rightbtn];
    [view addSubview:leftbtn];
    [self.view addSubview:view];
}
-(BOOL)textFieldShouldReturn:(UITextField *)theTextField
{
    [self.filed resignFirstResponder];
    if(theTextField.text.length>0)
    {
        NSArray* array=[[NSUserDefaults standardUserDefaults]objectForKey:@"searchArr"];
        NSMutableArray* newArr=[NSMutableArray new];
        NSString* str=self.filed.text;
        if([array containsObject:str])
        {
            [newArr addObjectsFromArray:array];
            for(int i=0;i<newArr.count;i++)
            {
                if([newArr[i] isEqualToString:str])
                {
                    [newArr removeObjectAtIndex:i];
                }
            }
            [newArr insertObject:str atIndex:0];
        }else
        {
            [newArr addObjectsFromArray:array];
            for(int i=0;i<newArr.count;i++)
            {
                if([newArr[i] isEqualToString:str])
                {
                    [newArr removeObjectAtIndex:i];
                }
            }
            [newArr insertObject:str atIndex:0];
        }
        //保存好
        [[NSUserDefaults standardUserDefaults]setObject:newArr forKey:@"searchArr"];
        [self upDateUI];
    }
    if(self.filed.text.length>0)
    {
        [self getData];
    }
    return YES;
}
-(void)doneAction
{
    [self textFieldShouldReturn:self.filed];
}
-(void)changedTextValue:(UITextField*)filed
{
    if(filed.text.length==0)
    {
        self.tableview.alpha=0;
        self.hotSearch.alpha=1;
        self.history.alpha=1;
    }
}
/** 点击返回 */
-(void)leftBtnAction
{
    [self.navigationController popViewControllerAnimated:YES];
    if (self.navigationController.viewControllers.count == 1) {
        if ([ICMusicPlayManager sharedManager].narrowView) {
            [ICMusicPlayManager sharedManager].narrowView.frame = CGRectMake(0, SCREEN_HEIGHT - 50 - GCtabbarHeight, SCREEN_WIDTH, 50);
        }
    }
}
/** 点击取消 */
-(void)rightBtnAction
{
    [self.filed resignFirstResponder];
    [self.dataSource removeAllObjects];
    [self.tableview reloadData];
    self.tableview.alpha=0;
    self.hotSearch.alpha=1;
    self.history.alpha=1;
}

@end
